﻿/**
* @projectName  线程无关的消息循环队列
* @author       无为
* @date         2019-08-01
*/

#ifndef H_LQUEUE_H_
#define H_LQUEUE_H_

template<class T>
class LQueue
{
  public:
    LQueue():m_maxsize(5),
        m_pArray(nullptr)
    {
       resize(m_maxsize);
    }
    virtual ~LQueue()
    {
        delete []m_pArray;
    }

    void resize(int nsize)
    {
      if (m_pArray != nullptr) {
          delete[]m_pArray;
      }
      m_maxsize = nsize + 1;
      m_pArray = new T[m_maxsize];
      m_front = 0;
      m_rear = 0;
    }
    // insert to queue
    bool enqueue(const T v)
    {
       if(isFull()){
           return false;
       }
       m_pArray[m_front] = v;
       m_front = (m_front + 1)% m_maxsize;
       return true;
   }

   bool dequeue(T& v)
   {
        if(isEmpty()){  return false; }
        v = m_pArray[m_rear];
        m_rear = (m_rear + 1)% m_maxsize;
        return true;
   }

   bool peek(T& v)
   {
       if(isEmpty()){ return false; }
       v = m_pArray[m_rear];
       return true;
   }
   unsigned int size()
   {
       return (m_front - m_rear);
   }
   bool isEmpty()
   {
       return (m_front == m_rear);
   }
   bool isFull()
   {
      return ((m_rear == (m_front + 1)% m_maxsize)?true:false);
   }
   unsigned int maxsize() {
       return m_maxsize - 1;
   }
private:
    unsigned int m_front;
    unsigned int m_rear;
    unsigned int m_maxsize;
    T* m_pArray;
};
#endif
